package com.javaee.interceptor.Utils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
//登录创建cookie
public class loginCookies {
    public static void login(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        Cookie[] cookies = req.getCookies();
        Boolean flag = true;
        //如果记住用户名和密码
        if ("remember".equals(req.getParameter("remember"))) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("username")) {
                    flag = false;
                }
                if (cookie.getName().equals("password")) {
                    flag = false;
                }
            }
            //如果没有创建cookie则创建cookie
            if (flag) {
                //创建cookie，同时使用java库函数对传输过来的值进行转码，这里转成utf-8
               ManagerCookies.Createcookies(req,resp,"username",req.getParameter("username"));
                ManagerCookies.Createcookies(req,resp,"password",req.getParameter("password"));
            }
            //如果已经创建了cookie，则更新cookie中的值
            else {
                ManagerCookies.Updatecookies(req,resp,"username",req.getParameter("username"));
                ManagerCookies.Updatecookies(req,resp,"password",req.getParameter("password"));
            }
        } else
        //当不记住密码的时候，用一个立即死去的cookie覆盖掉之前的cookie完成对cookie的清除
        {
            ManagerCookies.Deletecookies(req,resp,"username");
            ManagerCookies.Deletecookies(req,resp,"password");
        }
    }
}
